package com.bjsxt.shop.back.springmvc.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bjsxt.shop.common.controller.BaseController;
import com.bjsxt.shop.common.util.ConstatFinalUtil;
import com.bjsxt.shop.common.util.PageInfoUtil;
import com.bjsxt.shop.goods.pojo.AGoods;
import com.bjsxt.shop.goods.pojo.AGoodsBrand;
import com.bjsxt.shop.goods.pojo.AGoodsBrandEnum;
import com.bjsxt.shop.goods.pojo.AGoodsCate;
import com.bjsxt.shop.goods.service.IGoodsService;
import com.bjsxt.shop.users.pojo.AAdmins;

/**
 * URL规划,拦截器拦截
 * @author WangshSxt
 *
 */
@Controller
@RequestMapping("/back/goods/")
public class GoodsBackController extends BaseController
{
	@Resource
	private IGoodsService goodsService;
	
	//品牌列表
	@RequestMapping("/brandList")
	public String brandList()
	{
		ConstatFinalUtil.SYS_LOGGER.info("---brandList--");
		return "/back/goods/brandList" ; 
	}

	//查询品牌列表
	@RequestMapping(value = "/brandListJSON",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String brandListJSON(String page,String rows)
	{
		ConstatFinalUtil.SYS_LOGGER.info("---brandListJSON--");
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(page, rows);
		Map<String, Object> condMap = new HashMap<String, Object>();
		/* 查询列表 */
		Map<String, Object> resultMap = this.goodsService.findCondListGoodsBrandService(pageInfoUtil, condMap);
		/* 数据 */
		List<AGoodsBrand> brandList = (List<AGoodsBrand>) resultMap.get("list");
		int totalRecord = Integer.valueOf(resultMap.get("totalRecord") + "");
		
		/* 拼装数据,json */
		JSONObject resultJSON = new JSONObject() ;
		resultJSON.put("total", totalRecord);
		
		/* 数据 */
		JSONArray dataArr = new JSONArray() ; 
		int count = 1 ; 
		for (Iterator iterator = brandList.iterator(); iterator.hasNext();)
		{
			AGoodsBrand brand = (AGoodsBrand) iterator.next();
			JSONObject brandJSON = brand.toJSON();
			brandJSON.put("count", count);
			
			/* brand对象变成JSON */
			dataArr.add(brandJSON);
			count ++ ;
		}
		resultJSON.put("rows", dataArr);
		return resultJSON.toJSONString(); 
	}
	
	//品牌添加
	@RequestMapping("/brandInsert")
	public String brandInsert()
	{
		ConstatFinalUtil.SYS_LOGGER.info("---brandInsert--");
		return "/back/goods/brandInsert" ; 
	}

	//品牌添加提交：返回JSON，code：0，info：""
	@RequestMapping(value = "/brandInsertSubmit",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String brandInsertSubmit(String pubtimeStr,AGoodsBrand goodsBrand,MultipartFile file,HttpSession session)
	{
		ConstatFinalUtil.SYS_LOGGER.info("---brandInsertSubmit--");
		JSONObject resultJSON = new JSONObject();
		
		ConstatFinalUtil.SYS_LOGGER.info("--file:{}--",file);
		//上传文件
		if(file != null && !"".equalsIgnoreCase(file.getOriginalFilename()))
		{
			String originalFilename = file.getOriginalFilename();
			String fileName = "";
			try
			{
				//把上传的文件传到FTP中
				//相对路径
				String relaPath = ConstatFinalUtil.CONFIG_JSON.getString("relaPath");
				relaPath += "/brand/" +this.dateFormatUtil.dateStr(new Date()) + "/";
				//uuid扩展名
				fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
				//上传图片
				boolean flag = this.ftpUtil.uploadFile(fileName, relaPath, file.getInputStream());
				//判断
				if(flag)
				{
					goodsBrand.setLogoPath(relaPath + fileName);
				}
			} catch (IOException e)
			{
				ConstatFinalUtil.SYS_LOGGER.error("上传文件失败了,文件名:{}",fileName,e);
			}
		
		}
		
		//自己来转换时间,就不用转换器了
		goodsBrand.setPubTime(this.dateFormatUtil.strDateTime(pubtimeStr));
		
		//把页面上木有赋值的属性,赋值一下,从Session中获取
		AAdmins adminsSess = (AAdmins) session.getAttribute("admins");
		goodsBrand.setAdminsId(adminsSess.getId());
		goodsBrand.setCreateTime(new Date());
		goodsBrand.setUpdateTime(new Date());
		//保存数据
		resultJSON = this.goodsService.saveOneGoodsBrandService(goodsBrand);
		
		return resultJSON.toString();
		
	}

	/*商品模块开始*/
	
	//打开商品的列表页面
	@RequestMapping("/goodsList")
	public String goodsList()
	{
		ConstatFinalUtil.SYS_LOGGER.info("==goodsList===");
		return "/back/goods/goodsList" ; 		
	}
	
	//查询商品列表
	@RequestMapping(value ="/goodsListJSON",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String goodsListJSON(HttpServletRequest request,String page,String rows,String keyword,String status,String st,String ed)
	{
		ConstatFinalUtil.SYS_LOGGER.info("==goodsList===");
		//处理get乱码
		/*try
		{
			keyword = new String(keyword.getBytes("ISO8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e)
		{			
			//e.printStackTrace();
		}*/
		
		//分页信息
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(page, rows);
		//搜索条件
		if(status == null)
		{
			status = "";
		}
		if(st == null)
		{
			st = "";
		}
		if(ed == null)
		{
			ed = "";
		}
		
		Date stDate = null;
		Date edDate = null;
		if(!"".equalsIgnoreCase(st) && !"".equalsIgnoreCase(ed))
		{
			//从字符串变成日期
			stDate = this.dateFormatUtil.strDateTime(st);
			edDate = this.dateFormatUtil.strDateTime(ed);
		}
		Map<String,Object> condMap = new HashMap<String,Object>();
		condMap.put("keyword", keyword);
		//判断状态
		if(!"".equalsIgnoreCase(status))
		{
			condMap.put("status", status);
		}
		condMap.put("stDate", stDate);
		condMap.put("edDate", edDate);
		//查询列表
		Map<String,Object> resultMap = this.goodsService.findCondListGoodsService(pageInfoUtil, condMap);
		List<AGoods> goodsList = (List<AGoods>) resultMap.get("list");
		int totalRecord = Integer.valueOf(resultMap.get("totalRecord") + "");
		//拼装JSON
		JSONObject resultJSON = new JSONObject();
		resultJSON.put("total", totalRecord);
		//数据
		JSONArray dataArr = new JSONArray();
		for (Iterator iterator = goodsList.iterator(); iterator.hasNext();)
		{
			AGoods goodsTemp = (AGoods) iterator.next();
			JSONObject brandJSON = goodsTemp.toJSON();
			//brand对象变成JSON
			dataArr.add(brandJSON);
		}		
		resultJSON.put("rows", dataArr);
		return resultJSON.toJSONString();		
	}	
	
	//打开商品添加的页面
	@RequestMapping("/goodsInsert")
	public String goodsInsert(Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--goodsInsert--");
		Map<String,Object> condMap = new HashMap<String,Object>();
		//查询所有启用的品牌
		condMap.clear();
		condMap.put("status", AGoodsBrandEnum.STATUS_ENABLE.getStatus());
		Map<String,Object> resultMap = this.goodsService.findCondListGoodsBrandService(null, condMap);
		
		List<AGoodsBrand> brandList = (List<AGoodsBrand>) resultMap.get("list");
		//放到作用域
		model.addAttribute("brandList",brandList);
		
		//查询分类
		List<AGoodsCate> goodsCateTreeList = this.goodsService.findTreeListCateService();
		System.out.println("goodsCateTreeList:"+goodsCateTreeList);
		//放到作用域
		model.addAttribute("goodsCateTreeList", goodsCateTreeList);

		return "/back/goods/goodsInsert";	
	}
	
	//商品添加页面提交
	@ResponseBody
	@RequestMapping(value="/goodsInsertSubmit",produces="text/html;charset=UTF-8")
	public String goodsInsertSubmit(AGoods goods,String pubtimeStr,HttpSession session,HttpServletRequest request)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--goodsInsertSubmit--");
		JSONObject resultJSON = new JSONObject();
		 //以分类为蓝本，查询用户选择的分类
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", goods.getCateId());
		//通过分类找json
		AGoodsCate goodsCate = this.goodsService.findOneGoodsCateService(condMap);
		JSONArray specArr = goodsCate.getSpecArr(); 
		//第一层循环：name
		for (Iterator iterator = specArr.iterator(); iterator.hasNext();)
		{
			JSONObject jsonTemp1 = (JSONObject) iterator.next();
			JSONArray keysArr = (JSONArray) jsonTemp1.get("keys");
			//第二层循环:keys
			for (Iterator iterator2 = keysArr.iterator(); iterator2.hasNext();)
			{
				JSONObject jsonKeyTemp2 = (JSONObject) iterator2.next();
				
				/* value从哪来? */
				String keyParam = "spec_" + jsonTemp1.get("name") + "_" + jsonKeyTemp2.get("name");
				/* key:是不确定的 */
				String value = request.getParameter(keyParam);
				jsonKeyTemp2.put("values", value);
			}
		}
		/* 将分类中的规格values由原来的数组变成了值 */
		goods.setSpec(specArr.toJSONString());

		AAdmins adminsSess = (AAdmins) session.getAttribute("admins");
		/* 为页面上木有显示的字段赋值 */
		
		/* 自己来转换时间,就不用转换器了 */
		goods.setPubTime(this.dateFormatUtil.strDateTime(pubtimeStr));
		
		/* 把页面上木有赋值的属性,赋值一下 */
		/* 从Session中获取 */
		goods.setAdminsId(adminsSess.getId());
		goods.setCreateTime(new Date());
		goods.setUpdateTime(new Date());
		
		//上传
		resultJSON = this.goodsService.saveOneGoodsService(goods);
		return resultJSON.toJSONString();		
	}
	
	/*商品模块结束*/
}
